package com.bluegalaxy.nhb.snapi.controller.api.ck;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bluegalaxy.nhb.service.AnalyseSqlService;
import com.bluegalaxy.nhb.snapi.core.common.OvervivwUtil;
import com.bluegalaxy.nhb.snapi.core.common.UntisCom;
import com.bluegalaxy.nhb.snservice.common.utils.DateUtil;
import com.bluegalaxy.nhb.snservice.common.utils.StringUtil;
import com.bluegalaxy.nhb.snservice.domain.constant.AppConstant;
import com.bluegalaxy.nhb.snservice.domain.constant.CkConstant;
import com.bluegalaxy.nhb.snservice.domain.vo.api.R;
import com.bluegalaxy.nhb.snservice.domain.vo.api.ck.*;
import com.bluegalaxy.nhb.snservice.service.ck.OverviewService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

/**
 * 基础指标监控
 */
@RestController
@RequestMapping(AppConstant.APPLICATION_NAME+"/event")
@Api(value = "事件分析", tags = "事件分析API")
public class EventController {
    private static Log log = LogFactory.getLog(EventController.class);

    @Autowired
    private OverviewService overviewService;
    @Resource
    private AnalyseSqlService sqlService;
    //同比
    private  final  static  String ONYEARFLOW="01";
    //环比
    private  final  static  String COMPARISON="02";


    @ResponseBody
    @PostMapping("/findEvent")
    @ApiOperation(value = "查询事件分析", notes = "查询事件分析列表")
    public R findEvent(@RequestBody OverviewReq  paramVO) {
        //String转json
        log.info("findEvent："+JSONObject.toJSONString(paramVO));
        List<OverviewItemReq> itemList = paramVO.getEventItemList();
        for (OverviewItemReq itemReq : itemList){
            String sSql = UntisCom.beforeFloatWhere(null,itemReq.getFieldName());
            if ("Y".equals(itemReq.getIsInt())){
                sSql = UntisCom.beforeWhere(itemReq.getMethodName(),itemReq.getFieldName());
            }
            if (StringUtil.isEmpty(itemReq.getFieldName())){
                sSql = UntisCom.beforeWhere(itemReq.getMethodName());
            }
            itemReq.setsSql(sSql);
            if (CkConstant.ct_virtual.equals(itemReq.getCategoryType())){
                itemReq.setEventValue(getVirtualEventValue(itemReq.getJsonParam()));
                itemReq.setwSql(getVirtualSql(itemReq.getJsonParam()));
//                itemReq.setEventName();
            }else{
                itemReq.setEventValue(itemReq.getEventName());
                itemReq.setwSql(sqlService.analyseSql(itemReq.getJsonParam(), CkConstant.m_event,CkConstant.eventItems));
            }
        }
        List<String> dateList= DateUtil.getBetweenDates(paramVO.getStartDate(),paramVO.getEndDate());

        List<OvervivwVO> overvivwVOList = overviewService.selectEventList(paramVO,itemList);
        List<OvervivwVO> combineList = null;
        if (StringUtil.isNotEmpty(paramVO.getStartContrastDate()) && StringUtil.isNotEmpty(paramVO.getEndContrastDate())){
            paramVO.setStartDate(paramVO.getStartContrastDate());
            paramVO.setEndDate(paramVO.getEndContrastDate());
            combineList = overviewService.selectEventList(paramVO,itemList);
        }

        List<OvervivwResVO> resVOList = new ArrayList<>();
        int i=0;
        for (OverviewItemReq itemReq : itemList){
            OvervivwResVO resVO = new OvervivwResVO();
            resVO.setEventName(itemReq.getEventName());
//            resVO.setOvervivwList(supplementList(overvivwVOList,dateList,itemReq.getEventName()+"_"+i,combineList));
            resVO.setOvervivwList(supplementList(overvivwVOList,dateList,itemReq.getEventName(),combineList));
            resVOList.add(resVO);
            i++;
        }
        log.info("findEvent res："+JSONObject.toJSONString(resVOList));
        return R.data(resVOList);
    }

    private List<OvervivwVO> supplementList(List<OvervivwVO> overvivwVOList,List<String> dateList,
                                            String eventName,List<OvervivwVO> combineList){
        List<OvervivwVO> resList = new ArrayList<>();
//        log.info("dateList ："+JSONObject.toJSONString(dateList));
//        log.info("supplementList json："+JSONObject.toJSONString(overvivwVOList));
        if (overvivwVOList == null || overvivwVOList.isEmpty()){
            for (String st : dateList){
                resList.add(OvervivwUtil.initVO(st));
            }
            return resList;
        }
        Map<String, List<OvervivwVO>> mapList = overvivwVOList.stream().collect(
                Collectors.groupingBy(a -> a.getEventName()));
//        log.info("mapList："+JSONObject.toJSONString(mapList));
        for (Map.Entry<String, List<OvervivwVO>> m : mapList.entrySet()) {
//            log.info(eventName+ " equals "+m.getKey() +" res " + eventName.equals(m.getKey()));
            if (eventName.equals(m.getKey())){
                for(String d : dateList){
                    OvervivwVO vo = OvervivwUtil.getOvervivwVO(d,m.getValue());
                    vo.setCombineCount(OvervivwUtil.getCombineEventCount(eventName,d,combineList));
                    resList.add(vo);
                }
            }

        }

        return resList;
    }

    private String getVirtualSql(JSONObject virtualParam){
        StringBuffer virtualSqls = new StringBuffer();
        if (virtualParam.containsKey("eventJson")){
            JSONArray jsonArray = virtualParam.getJSONArray("eventJson");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonParam = jsonArray.getJSONObject(i);
                virtualSqls.append(sqlService.analyseSql(jsonParam, CkConstant.m_event,CkConstant.eventItems));
            }

        }

        return virtualSqls.toString();
    }

    private String getVirtualEventValue(JSONObject virtualParam){
        StringBuffer values = new StringBuffer();
        if (virtualParam.containsKey("eventJson")){
            JSONArray jsonArray = virtualParam.getJSONArray("eventJson");
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonParam = jsonArray.getJSONObject(i);
                if (i != 0){
                    values.append(",");
                }
                values.append("'");
                values.append(jsonParam.getString("eventType"));
                values.append("'");
            }

        }

        return values.toString();
    }
}
